import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/event/LoginEvent.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/set/ArticleDetail.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/BlankToolBarTool.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';

class BindWxPage extends StatefulWidget {
  String openId, avatar, nickname, type, sex,unionId;
  BindWxPage(
      {Key key,
      @required this.openId,
      @required this.avatar,
      @required this.nickname,
      @required this.sex,
      this.unionId,
      @required this.type})
      : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return new BindWxView();
  }
}

TextEditingController codeController = new TextEditingController();
TextEditingController userController = new TextEditingController();
TextEditingController passController = new TextEditingController();
TextEditingController inviteController = new TextEditingController();

class BindWxView extends State<BindWxPage> {
  Timer _countdownTimer;
  int _countdownNum = 59;
  String codeString = "获取验证码";
  int codeStatus = 1;
  BlankToolBarModel barModel = BlankToolBarModel();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    barModel.outSideCallback = focusNodeChange;
  }

  void focusNodeChange() {
    setState(() {});
  }

  @override
  void dispose() {
    _countdownTimer.cancel();
    _countdownTimer = null;
    barModel.removeFocusListeners();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "绑定微信",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: BlankToolBarTool.blankToolBarWidget(
        context,
        model: barModel,
        body: Container(
            color: white,
            child: new ListView(
              children: <Widget>[
                new Column(
                  children: <Widget>[
                    loginTopImg(),
                    loginUserEditInput(),
                    new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0,
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0),
                      child: Divider(
                        height: 1,
                        color: Colors.grey,
                      ),
                    ),
                    loginUserCodeInput(),
                    new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0,
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0),
                      child: Divider(
                        height: 1,
                        color: Colors.grey,
                      ),
                    ),
                    loginPassEditInput(),
                    new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0,
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0),
                      child: Divider(
                        height: 1,
                        color: Colors.grey,
                      ),
                    ),
                    // new Padding(
                    //   padding: EdgeInsets.fromLTRB(
                    //       ScreenUtil.getInstance().setWidth(DP_100),
                    //       10.0,
                    //       ScreenUtil.getInstance().setWidth(DP_100),
                    //       0.0),
                    //   child: new Stack(
                    //     alignment: Alignment(1.0, 1.0),
                    //     children: <Widget>[
                    //       new Row(
                    //         children: <Widget>[
                    //           new Padding(
                    //             padding: EdgeInsets.all(5.0),
                    //             child: new Image.asset(
                    //               "images/icon_code.png",
                    //               scale: 1.7,
                    //             ),
                    //           ),
                    //           Text(' '),
                    //           new Expanded(
                    //               child: new TextField(
                    //             cursorColor: mainColor,
                    //             keyboardAppearance: Brightness.light,
                    //             controller: inviteController,
                    //             decoration: new InputDecoration(
                    //                 hintText: "请输入邀请码",
                    //                 border: InputBorder.none,
                    //                 hintStyle: TextStyle(
                    //                     fontSize: ScreenUtil.getInstance()
                    //                         .setSp(NORMAL_FONT_SIZE))),
                    //           )),
                    //         ],
                    //       ),
                    //       // new IconButton(
                    //       //     icon: new Image.asset(
                    //       //       "images/del_input.png",
                    //       //       width: ScreenUtil.getInstance().setWidth(DP_20),
                    //       //       height: ScreenUtil.getInstance().setWidth(DP_20),
                    //       //     ),
                    //       //     onPressed: () {
                    //       //       passController.clear();
                    //       //     })
                    //     ],
                    //   ),
                    // ),
                    loginButton(context),
                  ],
                )
              ],
            )),
      ),
    );
  }

// ignore: missing_function_parameters
  Widget loginTopImg() {
    return new Padding(
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_100)),
        child: Material(
          elevation: 10,
          color: Colors.transparent,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_30)),
          child: new Image.asset(
            'images/app_icon.png',
            fit: BoxFit.cover,
            width: ScreenUtil.getInstance().setHeight(DP_150),
            height: ScreenUtil.getInstance().setHeight(DP_150),
          ),
        ));
  }

  Widget loginUserEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          0.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_phone.png",
                  scale: 1.7,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                keyboardType: TextInputType.numberWithOptions(),
                maxLines: 1,
                keyboardAppearance: Brightness.light,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                cursorColor: mainColor,
                controller: userController,
                decoration: new InputDecoration(
                    hintText: "输入手机号",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          // new IconButton(
          //     icon: new Image.asset(
          //       "images/del_input.png",
          //       width: ScreenUtil.getInstance().setWidth(DP_20),
          //       height: ScreenUtil.getInstance().setWidth(DP_20),
          //     ),
          //     onPressed: () {
          //       userController.clear();
          //     })
        ],
      ),
    );
  }

  Widget loginUserCodeInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          10.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_safe.png",
                  scale: 1.7,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                controller: codeController,
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.numberWithOptions(),
                maxLines: 1,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                cursorColor: mainColor,
                decoration: new InputDecoration(
                    hintText: "输入验证码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          new Container(
            width: ScreenUtil.getInstance().setWidth(DP_200 + 5),
            height: ScreenUtil.getInstance().setHeight(DP_50),
            margin: EdgeInsets.fromLTRB(0, 0, 0, 8),
            decoration: new BoxDecoration(
              color:codeStatus == 0?Color.fromARGB(255, 99, 99, 99):mainColor,
                borderRadius: BorderRadius.circular(20.0)),
            child: new FlatButton(
              child: new Padding(
                padding: EdgeInsets.all(0.0),
                child: new Text(
                  codeString,
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
                ),
              ),
              onPressed: () {
                if (codeStatus == 0) {
                  return;
                }
                if (userController.text.isEmpty) {
                  Fluttertoast.showToast(msg: "请输入手机号");
                  return;
                }
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (_) {
                      return new NetLoadingDialog(
                        loadingText: "获取中...",
                        bgColor: Color.fromARGB(255, 0, 0, 0),
                        requestCallBack: null,
                        outsideDismiss: false,
                      );
                    });
                getPhoneCode();
              },
            ),
          )
        ],
      ),
    );
  }

  getPhoneCode() async {
    Map map = new Map();
    map['phone'] = userController.text;
    map['sign_type'] = SignType.SEND_PHONE_CODE;
    Response<String> response =
        await HttpUtil().post(Api.SEND_PHONE_CODE, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
    return true;
  }

  Widget loginPassEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          10.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_locket.png",
                  scale: 1.7,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                keyboardAppearance: Brightness.light,
                controller: passController,
                cursorColor: mainColor,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                decoration: new InputDecoration(
                    hintText: "请设置登录密码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
        ],
      ),
    );
  }

  Widget loginButton(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      height: ScreenUtil.getInstance().setWidth(DP_90),
      margin: EdgeInsets.only(top:30),
      decoration: new BoxDecoration(
          color: mainColor, borderRadius: BorderRadius.circular(DP_80)),
      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
      child: new FlatButton(
        child: new Padding(
          padding: EdgeInsets.all(0.0),
          child: new Text(
            "立即绑定",
            style: new TextStyle(
                color: Colors.white,
                fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
          ),
        ),
        onPressed: () {
          _checkSub(context);
        },
      ),
    );
  }

  void toFindPwd() {
    print("找回密码");
  }

  void toRegister() {
    print("用户注册");
  }

  void _checkSub(BuildContext context) {
    String msgStr = "";
    if (!userController.text.isNotEmpty) {
      msgStr = "请输入手机号";
    } else if (!codeController.text.isNotEmpty) {
      msgStr = "请输入短信验证码";
    } else if (!passController.text.isNotEmpty) {
      msgStr = "请输入登录密码";
    }
    if (msgStr != '') {
      showDialog(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提示信息"),
              content: new Text(msgStr),
              actions: <Widget>[
                new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              ],
            );
          });
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: "綁定中...",
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
      register();
    }
  }

  register() async {
    Map map = new Map();
    map['phone'] = userController.text;
    map['pwd1'] = passController.text;
    map['code'] = codeController.text;
    map['openid'] = widget.openId;
    map['type'] = widget.type;
    map['unionid']=widget.unionId;
    map['nickname'] = widget.nickname;
    map['avatar'] = widget.avatar;
    map['sex'] = widget.sex;
    map['sign_type'] = SignType.BIND_WX;
    Response<String> response =
        await HttpUtil().post(Api.BIND_WX, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      saveString(TOKEN, userMap['data']['token']);
      saveString(UID, userMap['data']['uid'].toString());
      saveString(GROUP_ID, userMap['data']['group_id'].toString());
      saveString(PHONE, userController.text);
      APPLIC.eventBus.fire(LoginEvent());
      Navigator.of(context).pop();
      Navigator.of(context).pop();
    }
    return true;
  }
}
